package org.ehe.finance.receipt.controller;

import cn.dev33.satoken.annotation.SaCheckPermission;
import io.swagger.v3.oas.annotations.Parameter;
import lombok.RequiredArgsConstructor;
import org.ehe.common.core.BaseController;
import org.ehe.common.core.domain.R;
import org.ehe.common.log.annotation.Log;
import org.ehe.common.log.enums.BusinessType;
import org.ehe.common.mybatis.core.page.PageQuery;
import org.ehe.common.mybatis.core.page.TableDataInfo;
import org.ehe.finance.receipt.domain.ErpFinanceReceipt;
import org.ehe.finance.receipt.domain.bo.ReceiptBo;
import org.ehe.finance.receipt.domain.vo.ReceiptResponseVO;
import org.ehe.finance.receipt.mapper.ReceiptMapper;
import org.ehe.finance.receipt.service.ReceiptService;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.Arrays;
import java.util.List;

/**
 * 收款单管理
 * @author :zhangnn
 * @className :ReceiptController
 * @description: TODO
 * @date 2025-09-02 14:31:01
 */
@RestController
@RequestMapping("/finance/receipt")
@RequiredArgsConstructor
public class ReceiptController extends BaseController {

    private final ReceiptService receiptService;

    /**
     * 分页查询收款单
     * @param queryVO 查询条件
     * @param pageQuery 分页参数
     * @return 分页结果
     */
    @SaCheckPermission("finance:receipt:list")
    @GetMapping("/list")
    public TableDataInfo<ReceiptResponseVO> list(ReceiptBo queryVO, PageQuery pageQuery) {
        TableDataInfo<ReceiptResponseVO> page = receiptService.selectReceiptPage(queryVO, pageQuery);
        return page;
    }

    /**
     * 查询收款单详情
     * @param id 收款单ID
     * @return 收款单详情
     */
    @SaCheckPermission("finance:receipt:query")
    @GetMapping("/{id}")
    public R<ErpFinanceReceipt> getInfo(@Parameter(description = "收款单ID") @PathVariable Long id) {
        ErpFinanceReceipt receipt = receiptService.getReceiptDetail(id);
        return R.ok("查询收款单详情成功", receipt);
    }

    /**
     * 创建收款单
     * @param receiptBo 收款单业务对象
     * @return 操作结果
     */
    @SaCheckPermission("finance:receipt:add")
    @Log(title = "收款单", businessType = BusinessType.INSERT)
    @PostMapping
    public R<Void> add(@Validated @RequestBody ReceiptBo receiptBo) {
        boolean result = receiptService.createReceipt(receiptBo);
        return toAjax(result);
    }

    /**
     * 更新收款单
     * @param receiptBo 收款单业务对象
     * @return 操作结果
     */
    @SaCheckPermission("finance:receipt:edit")
    @Log(title = "收款单", businessType = BusinessType.UPDATE)
    @PutMapping
    public R<Void> edit(@Validated @RequestBody ReceiptBo receiptBo) {
        boolean result = receiptService.updateReceipt(receiptBo);
        return toAjax(result);
    }

    /**
     * 删除收款单
     * @param ids 收款单ID，多个用逗号分隔
     * @return 操作结果
     */
    @SaCheckPermission("finance:receipt:remove")
    @Log(title = "收款单", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public R<Void> remove(@Parameter(description = "收款单ID，多个用逗号分隔") @PathVariable String ids) {
        List<Long> idList = Arrays.stream(ids.split(","))
            .map(Long::parseLong)
            .toList();

        if (idList.size() == 1) {
            return toAjax(receiptService.deleteReceipt(idList.get(0)));
        } else {
            return toAjax(receiptService.batchDeleteReceipt(idList));
        }
    }

    /**
     * 更新收款金额
     * @param id 收款单ID
     * @param amount 收款金额
     * @return 操作结果
     */
    @SaCheckPermission("finance:receipt:payment")
    @Log(title = "收款单收款", businessType = BusinessType.UPDATE)
    @PutMapping("/{id}/receipt")
    public R<Boolean> updateReceipt(@Parameter(description = "收款单ID") @PathVariable Long id,
                                    @Parameter(description = "收款金额") @RequestParam BigDecimal amount) {
        boolean result = receiptService.updateReceiptAmount(id, amount);
        return R.ok("收款单收款成功", result);
    }

    /**
     * 查询即将到期收款
     * @param days 天数，默认7天
     * @return 即将到期收款列表
     */
    @SaCheckPermission("finance:receipt:due")
    @GetMapping("/due")
    public R<List<ErpFinanceReceipt>> getDueReceipts(@Parameter(description = "天数，默认7天")
                                                     @RequestParam(defaultValue = "7") int days) {
        List<ErpFinanceReceipt> dueReceipts = receiptService.getDueReceipts(days);
        return R.ok("查询即将到期收款成功", dueReceipts);
    }

    /**
     * 客户收款统计
     * @return 统计结果
     */
    @SaCheckPermission("finance:receipt:statistics")
    @GetMapping("/statistics/customer")
    public R<List<ReceiptMapper.ReceiptStatistics>> getCustomerStatistics() {
        List<ReceiptMapper.ReceiptStatistics> statistics =
            receiptService.getReceiptStatisticsByCustomer();
        return R.ok("客户收款统计成功", statistics);
    }

    /**
     * 生成收款单号
     * @return 收款单号
     */
    @SaCheckPermission("finance:receipt:add")
    @GetMapping("/generate-receipt-no")
    public R<String> generateReceiptNo() {
        String receiptNo = receiptService.generateReceiptNo();
        return R.ok("生成收款单号成功", receiptNo);
    }

    /**
     * 审核收款单
     * @param id 收款单ID
     * @return 操作结果
     */
    @SaCheckPermission("finance:receipt:audit")
    @Log(title = "审核收款单", businessType = BusinessType.UPDATE)
    @PutMapping("/{id}/audit")
    public R<Void> audit(@Parameter(description = "收款单ID") @PathVariable Long id) {
        boolean result = receiptService.auditReceipt(id);
        return toAjax(result);
    }

    /**
     * 反审核收款单
     * @param id 收款单ID
     * @return 操作结果
     */
    @SaCheckPermission("finance:receipt:audit")
    @Log(title = "反审核收款单", businessType = BusinessType.UPDATE)
    @PutMapping("/{id}/unaudit")
    public R<Void> unaudit(@Parameter(description = "收款单ID") @PathVariable Long id) {
        boolean result = receiptService.unauditReceipt(id);
        return toAjax(result);
    }

    /**
     * 检查收款单号是否存在
     * @param receiptNo 收款单号
     * @param id 排除的ID
     * @return 检查结果
     */
    @SaCheckPermission("finance:receipt:query")
    @GetMapping("/check-receipt-no")
    public R<Boolean> checkReceiptNoExists(@Parameter(description = "收款单号") @RequestParam String receiptNo,
                                           @Parameter(description = "排除的ID") @RequestParam(required = false) Long id) {
        boolean exists = receiptService.checkReceiptNoExists(receiptNo, id);
        return R.ok("检查收款单号完成", exists);
    }

//    /**
//     * 导出收款单
//     * @param response HTTP响应
//     * @param queryVO 查询条件
//     */
//    @SaCheckPermission("finance:receipt:export")
//    @Log(title = "收款单", businessType = BusinessType.EXPORT)
//    @PostMapping("/export")
//    public void export(HttpServletResponse response, @RequestBody ReceiptBo queryVO) {
//        // 不分页查询所有数据
//        PageQuery pageQuery = new PageQuery();
//        pageQuery.setPageNum(1);
//        pageQuery.setPageSize(Integer.MAX_VALUE);
//
//        List<ReceiptResponseVO> list = receiptService.selectReceiptPage(queryVO, pageQuery).getRecords();
//        ExcelUtil<ReceiptResponseVO> util = new ExcelUtil<>(ReceiptResponseVO.class);
//        util.exportExcel(response, list, "收款单数据");
//    }
}
